package main

import (
	"context"
	"flag"
	"fmt"
	"time"

	"github.com/smallnest/rpcx/server"
)

var (
	addr = flag.String("addr", "localhost:8973", "server address")
)

func main() {
	flag.Parse()

	s := server.NewServer()
	//s.RegisterName("Arith", new(example.Arith), "")
	s.Register(new(Arith), "")
	fmt.Println(s.Serve("tcp", *addr))
	ch := make(chan int)
	<- ch
}

type Args struct {
	A int
	B int
}

type Reply struct {
	C int
}

type Arith int

func (t *Arith) Mul(ctx context.Context, args *Args, reply *Reply) error {
	//fmt.Println("call in mul")
	//fmt.Println(fmt.Sprintf("%+v %s", ctx, time.Now()))
	t1, ok := ctx.Deadline()

	if ok {
		v := t1.Sub(time.Now())
		if v > 0 {
			fmt.Println("v", v)
			var f context.CancelFunc
			fmt.Println("ctx1",ctx)
			ctx, f = context.WithTimeout(ctx, v)
			defer f()
		}
	}
	fmt.Println("ctx2",ctx)
	timeout1(ctx, args, reply)

	return nil
}

func timeout1(ctx context.Context, args *Args, reply *Reply) {
	time.Sleep(5 * time.Second)
	reply.C = args.A * args.B
	fmt.Printf("call: %d * %d = %d %s \n", args.A, args.B, reply.C, time.Now())
}
